package cn.xuewenbao.ucenter.service.impl;

import cn.xuewenbao.ucenter.entity.Member;
import cn.xuewenbao.ucenter.entity.Message;
import cn.xuewenbao.ucenter.entity.vo.MemberMesVo;
import cn.xuewenbao.ucenter.mapper.MessageMapper;
import cn.xuewenbao.ucenter.service.MemberService;
import cn.xuewenbao.ucenter.service.MessageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.sf.saxon.expr.Component;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mafayu
 * @since 2021-05-24
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Autowired
    private MemberService memberService;

    //获得私信列表页面
    @Override
    public Result<List<MemberMesVo>> getMemberList(String userId) {
        Result<List<MemberMesVo>> result = new Result<>();
        QueryWrapper<Message> wrapper = new QueryWrapper<>();
        wrapper.eq("send_id", userId).or().eq("receive_id", userId).orderByDesc("gmt_create");
        List<Message> messageList = baseMapper.selectList(wrapper);
        if (messageList==null){
            result.setMessage("私信列表为空");
            result.setSuccess(true);
            return result;
        }
        //获得私信用户id和最新一条信息内容
        Map<String, String> map = new LinkedHashMap<>();
        for (Message message : messageList) {
            String id = message.getSendId().equals(userId) ? message.getReceiveId() : message.getSendId();
            String context = message.getContext();
            map.putIfAbsent(id, context);
        }
        //封装对象
        List<MemberMesVo> mesVoList = new LinkedList<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String id = entry.getKey();
            String context = entry.getValue();
            Member member = memberService.getById(id);
            MemberMesVo memberMesVo = new MemberMesVo();
            BeanUtils.copyProperties(member, memberMesVo);
            memberMesVo.setContext(context);
            mesVoList.add(memberMesVo);
        }
        result.setResult(mesVoList);
        result.setMessage("查询成功");
        result.setSuccess(true);
        return result;
    }

}
